<template>
  <div class="yy-schedule-setting">
    <el-dialog
        v-model="isVisible"
        title="设置排班"
        width="90%"
        :close-on-click-modal="false"
        @close="onCancelDialog"
        :show-close="true"
        class="yy-modal--custom"
        append-to-body
    >
      <div style="margin-bottom: 5px;font-size: 16px; display: flex; padding: 10px 10px;
      background: #f1f1f1;">
        <el-select v-model="selectItemDept" placeholder="请选择科目" @change="onSelectItemChange" style="min-width: 120px; flex:1;">
          <el-option :label="item.name" :value="item.id" v-for="item in regItems" :key="item.id"/>
        </el-select>

        <el-select v-if="false" v-model="form.category" placeholder="请选择类别" @change="onSelectCategoryChange" style="min-width: 120px; flex:1;">
          <el-option :label="item.name" :value="item.id" v-for="item in regCategorys" :key="item.id"/>
        </el-select>

      </div>
      <div class="yy-schedule-setting_list">
        <div class="yy-schedule-setting_list-item" v-for="week in weekArr" :key="week.key">
          <div>
            <el-select size="small" v-model="week.value" disabled>
              <el-option v-for="w in weekArr" :key="w.key" :value="w.value" :label="w.label"></el-option>
            </el-select>
          </div>
          <div>
            <el-select size="small" v-model="form[week.key]">
              <el-option v-for="clinic in clinicHoursArr" :key="clinic.value" :value="clinic.value" :label="clinic.label"></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancelDialog">关闭</el-button>
          <el-button type="primary" @click="onSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

</template>
<script setup lang="ts">
import {reactive, defineEmits, defineProps, defineExpose, ref, onBeforeMount} from "vue";
import {QueueScheduleModel} from "@/model/QueueScheduleModel";
import DoctorClientApi from "@/api/doctor";
import RegCategoryApi from "@/api/queue/RegCategoryApi";
import {QueueRegCategoryModel} from "@/model/QueueRegCategoryModel";
import RegItemApi from "@/api/queue/RegItemApi";
import {QueueRegItemModel} from "@/model/QueueRegItemModel";
import {formatDate} from "@/utils";
import {ElMessage} from "element-plus";

const clinicHoursArr: {label: string, value: number}[] = [
  {label: '休息', value: 0}, {label:'上午', value: 1}, {label: '下午', value: 3}, {label: '全天', value: 5}
]
const weekArr = ref<{label: string,key: string, value:number}[]>([
  {label: '星期一', key:'monday', value: 1}, {label:'星期二', key: 'tuesday', value: 2},
  {label: '星期三', key: 'wednesday', value: 3}, {label: '星期四', key: 'thursday', value: 4},
  {label: '星期五', key: 'friday', value: 5}, {label: "星期六", key: 'saturday', value: 6},
  {label:'星期日', key: 'sunday', value: 7}
])
const getWeekKeyByVal = (val) => weekArr.value.find(week => week.value === val)?.key

const $emit = defineEmits({
  'selectSchedule': (schedule) => schedule
})
const isVisible = ref(false)

const regCategorys = ref<QueueRegCategoryModel[]>([])

const regItems = ref<QueueRegItemModel[]>([])
const selectItemDept = ref()
const form = reactive({
  dept: '',
  item: '',
  category: '',
  monday: 0,
  tuesday: 0,
  wednesday: 0,
  thursday: 0,
  friday: 0,
  saturday: 0,
  sunday: 0,
  _default: {
    monday: {id: '', clinicHoursId: 0},
    tuesday: {id: '', clinicHoursId: 0},
    wednesday: {id: '', clinicHoursId: 0},
    thursday: {id: '', clinicHoursId: 0},
    friday: {id: '', clinicHoursId: 0},
    saturday: {id: '', clinicHoursId: 0},
    sunday: {id: '', clinicHoursId: 0},
  }
})

const currentEmployee = ref()
const currentSchedule = ref<QueueScheduleModel>()

const onShowDialog = (employee, schedule: QueueScheduleModel, serverTime: number) => {
  currentEmployee.value = employee
  currentSchedule.value = schedule
  if (currentSchedule.value) {
    form.dept = currentSchedule.value.departId
    form.item = currentSchedule.value.itemId
    form.category = currentSchedule.value.categoryId
    selectItemDept.value = form.item + "_" + form.dept
  }
  Promise.all([listRegCategory(),listDoctorRegItem()]).then(() => {
      listSchedule()
  })
  isVisible.value = true
}

const listDoctorRegItem = () => {
  return new Promise((resolve, reject) => {
    RegItemApi.listAllRegItem(null, currentEmployee.value.emplId).then((items) => {
      regItems.value = items ? items.map(item => Object.assign({
        id: item.id + "_" + item.deptId,
        name: item.name + `(${item.deptName})`
      })) : []
      if (items?.length && !form.item) {
        form.item = items[0].id
        form.dept = items[0].deptId
        selectItemDept.value = items[0].id + "_" + items[0].deptId
      }
      resolve(items)
    }, (err) => reject(err))
  })
}

const listRegCategory = () => {
  return new Promise((resolve, reject) => {
    RegCategoryApi.listRegCategory().then((data) => {
      regCategorys.value = data
      if (data?.length) {
        form.category = data.find(item => item.categoryFlag === 0).id
      }
      resolve(data)
    }, (err) => reject(err))
  })
}

const listSchedule = () => {
  if (form.dept && form.item && form.category && currentEmployee.value.emplId) {
    DoctorClientApi.listScheduleByEmplId(currentEmployee.value.emplId, form.dept, form.item, form.category).then(schedules => {
      schedules.forEach(schedule => {
        form[getWeekKeyByVal(schedule.scheduleWeek)] = schedule.clinicHoursId
        form._default[getWeekKeyByVal(schedule.scheduleWeek)] = {id: schedule.id, clinicHoursId: schedule.clinicHoursId}
      })
    })
  }
}

const onSelectItemChange = () => {
  const deptAndItem = selectItemDept.value.split("_")
  form.dept = deptAndItem[1]
  form.item = deptAndItem[0]
  form.monday = 0
  form.tuesday = 0
  form.wednesday = 0
  form.thursday = 0
  form.friday = 0
  form.saturday = 0
  form.sunday = 0
  form._default = {
    monday: {id: '', clinicHoursId: 0},
    tuesday: {id: '', clinicHoursId: 0},
    wednesday: {id: '', clinicHoursId: 0},
    thursday: {id: '', clinicHoursId: 0},
    friday: {id: '', clinicHoursId: 0},
    saturday: {id: '', clinicHoursId: 0},
    sunday: {id: '', clinicHoursId: 0},
  }
  listSchedule()
}

const onSelectCategoryChange = () => {
  // listSchedule()
}


const onSave = () => {
  if(!form.item) {
    ElMessage.warning("请选择科目")
    return
  }
  const scheduleList = []
  weekArr.value.forEach((week) => {
     if (form[week.key] != form._default[week.key].clinicHoursId) {
       const data = new QueueScheduleModel().deserialize(Object.assign({}, {
         id: form._default[week.key].id || undefined,
         departId: form.dept,
         itemId: form.item,
         categoryId: form.category,
         doctorId: currentEmployee.value.emplId,
         scheduleWeek: week.value,
         clinicHoursId: form[week.key],
         flowFlag: 1
       }))
       scheduleList.push(data)
     }
  })
  if (scheduleList.length) {
    DoctorClientApi.scheduleSetting(currentEmployee.value.emplId, scheduleList).then((data) => {
      ElMessage.success("保存成功")
      $emit('selectSchedule', true)
      onCancelDialog()
    })
  }
}


const onCancelDialog = () => {
  if (isVisible.value) {
    setTimeout(() => {
      form.dept = ''
      form.item = ''
      form.category = ''
      form.monday = 0
      form.tuesday = 0
      form.wednesday = 0
      form.thursday = 0
      form.friday = 0
      form.saturday = 0
      form.sunday = 0
      form._default = {
        monday: {id: '', clinicHoursId: 0},
        tuesday: {id: '', clinicHoursId: 0},
        wednesday: {id: '', clinicHoursId: 0},
        thursday: {id: '', clinicHoursId: 0},
        friday: {id: '', clinicHoursId: 0},
        saturday: {id: '', clinicHoursId: 0},
        sunday: {id: '', clinicHoursId: 0},
      }
    }, 200)
  }
  isVisible.value = false
}

defineExpose({
  onShowDialog
})

</script>
<style scoped lang="scss">
.yy-schedule-setting_list {
  max-height: 300px;
  overflow-y: auto;
  &-item {
    display: flex;
    & > div:nth-child(1) {
      flex: 2;
    }
    & > div:nth-child(2) {
      flex: 1;
    }
    & > div:nth-child(3) {
      justify-content: flex-end;
      flex: 1;
    }
    & > div {
      display: inline-flex;
      align-items: center;
      padding: 5px 10px;
    }
  }
}
</style>
